const axios = require('axios')
var http = require('http')
var iconv = require('iconv-lite');
var BufferHelper = require('bufferhelper');
var fs = require('fs')
var path = require('path')

var md5 = require("md5")
const service = axios.create({
    timeout: 30000,
    withCredentials: true
})
class AxiosController {
    constructor() {
        this.baseSrc = `D:/requestCacheMd5/`
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
    }

    get(options) {
        return new Promise((resolve, reject) => {
            service.get(options.url, {
                params: options.data || {},
                headers: {
                    UserAgent: `Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36`,
                    Accept: `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8`,
                    AcceptLanguage: `zh-CN,zh;q=0.9,en;q=0.8`,
                    Cookie: `cid=90e41008aff7ca97caa44a51bb95b4601533639008; ComputerID=90e41008aff7ca97caa44a51bb95b4601533639008; PHPSESSID=d89ca10c7ba81d778253182d7554bead; v=Av1IN4KTenbD3d6aR3YCkw3bDFLzmjHsO86VwL9COdSD9hOEh-pBvMsepdVM`,
                }
            }).then(function (response) {
                resolve(response)
            }).catch(function (error) {
                reject(error)
            })
        })
    }
    post() {
        return new Promise((resolve, reject) => {
            service.post(options.url, { params: options.data || {} })
                .then(function (response) {
                    resolve(response)
                })
                .catch(function (error) {
                    reject(error)
                })
        })
    }

    request(options) {
        let self = this;
        return new Promise(async (resolve, reject) => {
            console.log(options.url)
            var url = require('url').parse(options.url);
            let urlMd5 = md5(url.href)
            let fileSrc = this.baseSrc + urlMd5;
            try {
                if (!options.isCache || !fs.existsSync(fileSrc)) {
                    http.get(url, function (res) {
                        var bufferHelper = new BufferHelper();
                        res.on('data', function (chunk) {
                            bufferHelper.concat(chunk);
                        });
                        res.on('end', async function () {
                            let data = iconv.decode(bufferHelper.toBuffer(), options.encode)
                            if (data.indexOf(`<div class="K">403</div>`) != -1) {
                                console.log(`<------------------------0>`)
                                console.log('\t403')
                                console.log(`<------------------------0>`)
                                await self.sleep()
                                let data = await self.request(options)
                                resolve(data)
                            } else if (data.indexOf(`<h1>504 Gateway Time-out</h1>`) != -1) {
                                console.log(`<------------------------1>`)
                                console.log('\t504')
                                console.log(`<------------------------1>`)
                                await self.sleep()
                                let data = await self.request(options)
                                resolve(data)
                            } else {
                                fs.writeFileSync(fileSrc, data)
                                resolve(data)
                            }

                        });
                    }).on('error', async function (err) {
                        console.log(`<------------------------2>`)
                        console.log(err)
                        console.log(`<------------------------2>`)
                        await self.sleep()
                        let data = await self.request(options)
                        resolve(data)
                    })
                } else {
                    console.log(`urlMd5--->${urlMd5}`)
                    resolve(fs.readFileSync(fileSrc))
                }
            } catch (err) {
                console.log(`<------------------------3>`)
                console.log(err)
                console.log(`<------------------------3>`)
                await self.sleep()
                let data = await self.request(options)
                resolve(data)
            }
        })
    }

    sleep() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve()
            }, 1000 * 3)
        })
    }
    mkdirs(dirpath) {
        if (!fs.existsSync(path.dirname(dirpath))) {
            this.mkdirs(path.dirname(dirpath));
        }
        fs.mkdirSync(dirpath);
    }

    proxy(options) {
        return new Promise((resolve, reject) => {
            options = Object.assign({ method: 'GET' }, options)
            http.get(options, function (res) {
                var bufferHelper = new BufferHelper();
                res.on('data', function (chunk) {
                    bufferHelper.concat(chunk);
                });
                res.on('end', function () {
                    let data = iconv.decode(bufferHelper.toBuffer(), 'UTF-8')
                    console.log(data)
                    resolve(data)
                }).on('error', function (e) {
                    console.log("Get error: " + e.message);
                })
            }).on('error', function (err) {
                console.log('-------------------')
                reject(err)
            })
        })
    }
}

module.exports = AxiosController




//-------------------------
// var http = require('http')
// var iconv = require('iconv-lite');
// var BufferHelper = require('bufferhelper');
// let o_url = `http://data.eastmoney.com/DataCenter_V3/yjfp/getlist.ashx?js=var%20vGrLQhgX&pagesize=50&page=1&sr=-1&sortType=YAGGR&mtk=%C8%AB%B2%BF%B9%C9%C6%B1&filter=(ReportingPeriod=^2018-06-30^)&rt=51118198`

// function get(isUseProxy) {
//     var url = require('url').parse(o_url);
//     let options = {};
//     if (isUseProxy) {
//         options = {
//             host: '117.85.81.94',
//             port: '53128',
//             method: 'GET',
//             path: url.href
//         }
//     } else {
//         options = {
//             host: url.host,
//             path: url.path,
//             method: 'GET'
//         }
//     }

//     http.get(options, function (res) {
//         var bufferHelper = new BufferHelper();
//         res.on('data', function (chunk) {
//             bufferHelper.concat(chunk);
//         });
//         res.on('end', function () {
//             let data = iconv.decode(bufferHelper.toBuffer(), 'UTF-8')
//             console.log(data)
//         }).on('error', function (e) {
//             console.log("Get error: " + e.message);
//         })
//     })

// }

// get(false)